package com.tbit.uqbike.client.util;

import com.tbit.uqbike.client.pojo.newEntity.DivMembers;
import com.tbit.uqbike.client.pojo.newEntity.UserAdaPayLog;
import com.tbit.uqbike.client.pojo.newEntity.UserDivide;

import java.math.BigDecimal;
import java.math.RoundingMode;
import java.util.ArrayList;
import java.util.Comparator;
import java.util.List;
import java.util.Objects;
import java.util.stream.Collectors;

/**
 * @Author: chen
 * @Description: 分账
 * @Date: 创建于 9:52 2022/2/23
 */
public class AdapayUtil {

    /**
     * 获取分账用户信息
     *
     * @param divides
     * @param money
     * @return
     */
    public static List<DivMembers> getCashUserCopy(List<UserDivide> divides, Double money,
                                               UserDivide userDivide) {
        List<DivMembers> list = new ArrayList<>();
        /**兼容服务费账号*/
        if (userDivide != null) {
            /**计算服务费大于1分才可以计算*/
            if (money / 100 * userDivide.getProportion() >= 0.01) {
                double feeMoney = money / 100 * userDivide.getProportion();
                // 分之后的数据进行四舍五入处理
                BigDecimal bd = new BigDecimal(feeMoney);
                bd = bd.setScale(2, RoundingMode.HALF_EVEN);
                double roundFeeMoney = bd.doubleValue();
                String caseMoney = doubleCase(roundFeeMoney);
                DivMembers divMembers = new DivMembers(userDivide.getUserNO(), String.valueOf(caseMoney), "N");
                list.add(divMembers);
                money = money - DoubleUtil.parseDouble(Double.parseDouble(divMembers.getAmount()) * 100);
            }

        }
        /**未配置分账账号，直接分账到品牌账号,商户本身时，传入0*/
        if (divides == null || divides.isEmpty()) {
            DivMembers divMembers = new DivMembers("0", String.format("%.2f", money / 100), "Y");
            list.add(divMembers);
        } else {
            Double laveMoney = money / 100;
            divides = divides.stream().sorted(Comparator.comparing(UserDivide::getMainUser)).collect(
                    Collectors.toList());
            for (UserDivide user : divides) {
                String fee_flag = "N";
                /**计算分账金额*/
                double cashMoneyValue = money / 100 * user.getProportion();
                // 分之后的数据进行四舍五入处理
                BigDecimal bd = new BigDecimal(cashMoneyValue);
                bd = bd.setScale(2, RoundingMode.HALF_EVEN);
                double cashMoney = bd.doubleValue();
                String caseMoney = doubleCase(cashMoney);
                laveMoney = laveMoney - Double.parseDouble(caseMoney);
                if (user.getMainUser() == 1 && laveMoney > 0) {
                    caseMoney = String.format("%.2f", Double.parseDouble(caseMoney) + laveMoney);
                }
                if (user.getMainUser() == 1) {
                    fee_flag = "Y";
                }
                DivMembers divMembers = new DivMembers(user.getUserNO(), String.valueOf(caseMoney), fee_flag);
                list.add(divMembers);

            }
        }
        return list;
    }

    /**
     * 获取分账用户信息(新 去除1分限制)
     *
     * @param divides
     * @param money
     * @return
     */
    public static List<DivMembers> getCashUser(List<UserDivide> divides, Double money,
                                               UserDivide userDivide) {
        List<DivMembers> list = new ArrayList<>();
//        /**用户余额小于0.1元直接分账到商户*/
//        if (money <= 10) {
//            DivMembers divMembers = new DivMembers("0", String.format("%.2f", money / 100), "Y");
//            list.add(divMembers);
//            return list;
//        }

        /**兼容服务费账号*/
        if (userDivide != null) {
            /**计算服务费大于1分才可以计算*/
            if (money / 100 * userDivide.getProportion() >= 0.01) {
                double feeMoney = money / 100 * userDivide.getProportion();
                // 分之后的数据进行四舍五入处理
                BigDecimal bd = new BigDecimal(feeMoney);
                bd = bd.setScale(2, RoundingMode.HALF_EVEN);
                double roundFeeMoney = bd.doubleValue();
                String caseMoney = doubleCase(roundFeeMoney);
                DivMembers divMembers = new DivMembers(userDivide.getUserNO(), String.valueOf(caseMoney), "N");
                list.add(divMembers);
                money = money - DoubleUtil.parseDouble(Double.parseDouble(divMembers.getAmount()) * 100);
            }

        }
        /**未配置分账账号，直接分账到品牌账号,商户本身时，传入0*/
        if (divides == null || divides.isEmpty()) {
            DivMembers divMembers = new DivMembers("0", String.format("%.2f", money / 100), "Y");
            list.add(divMembers);
        } else {
            divides = divides.stream().sorted(Comparator.comparing(UserDivide::getProportion)).collect(Collectors.toList());
            double totalMoney = money / 100;
            calculateDistribution(divides,totalMoney,list,0);
        }
        boolean hasFeeFlag = list.stream().anyMatch(x -> Objects.equals(x.getFee_flag(), "Y"));
        // 如果主商户因比例过小导致被剔除掉分账对象列表，选取分的最多的账户作为手续费承担方
        if (!hasFeeFlag){
            DivMembers maxDivMembers = list.get(list.size() - 1);
            maxDivMembers.setFee_flag("Y");
        }
        return list;
    }

    /**
     * 分组递归计算分账金额（银行家舍入）
     * @param proportions
     * @param totalAmount
     * @param divMembersList
     * @param startIndex
     */
    private static void calculateDistribution(List<UserDivide> proportions, double totalAmount, List<DivMembers> divMembersList, int startIndex) {
        // 递归结束条件
        int endIndex = proportions.size()-1;
        if((endIndex-startIndex) < 0){
            return ;
        }
        UserDivide userDivide = proportions.get(startIndex);
        double minProportion = userDivide.getProportion();
        double amount = round(totalAmount*minProportion);
        // 剔除分账金额为0的分账信息
        if (Double.compare(amount,0) != 0) {
            // 添加分账对象信息
            DivMembers divMembers = new DivMembers();
            divMembers.setAmount(String.format("%.2f",amount));
            divMembers.setMember_id(userDivide.getUserNO());
            String feeFlag = "N";
            if (userDivide.getMainUser() == 1){
                feeFlag = "Y";
            }
            divMembers.setFee_flag(feeFlag);
            divMembersList.add(divMembers);
        }

        // 剩余待分金额
        double remainingAmount = totalAmount - amount;
        remainingAmount = remainingAmount/(1-minProportion);
        calculateDistribution(proportions,remainingAmount,divMembersList,startIndex+1);
    }

    private static double round(double value) {
        // 使用BigDecimal进行银行家舍入
        BigDecimal bd = new BigDecimal(value).setScale(2, RoundingMode.HALF_EVEN);
        return bd.doubleValue();
    }

    public static void main(String[] args) {

        List<UserDivide> divides = new ArrayList<>();
        UserDivide userDivide = new UserDivide();
        userDivide.setMainUser(0);
        userDivide.setUserNO("hhh");
        userDivide.setProportion(0.18);
        divides.add(userDivide);
        UserDivide userDivide1 = new UserDivide();
        userDivide1.setMainUser(1);
        userDivide1.setUserNO("mmmm");
        userDivide1.setProportion(0.82);
        divides.add(userDivide1);
        /*UserDivide userDivide2 = new UserDivide();
        userDivide2.setMainUser(1);
        userDivide2.setUserNO("n");
        userDivide2.setProportion(0.3);
        divides.add(userDivide2);*/
        /*UserDivide userDivide3 = new UserDivide();
        userDivide3.setMainUser(0);
        userDivide3.setUserNO("TBIT");
        userDivide3.setProportion(0.04);*/
        System.out.println(divides);
        divides=divides.stream().sorted(Comparator.comparing(UserDivide::getMainUser)).collect(Collectors.toList());
        System.out.println("-------------"+divides);
        List<DivMembers> divMembersList = getCashUser(divides, 250D, null);
        System.out.println(divMembersList);
        for (DivMembers divMembers : divMembersList) {
            System.out.println((DoubleUtil.parseDouble(Double.parseDouble(divMembers.getAmount()) * 100)).intValue());
        }

        /*System.out.println((Double.parseDouble("0.57")));
        System.out.println((Double.parseDouble("0.57") * 100));
        System.out.println((int) (Double.parseDouble("0.57") * 100));*/
    }

    /**
     * 取小数点后两位
     *
     * @param temp
     * @return
     */
    public static String doubleCase(double temp) {
        String strNum = String.valueOf(temp);
        String ss = "";
        int a = strNum.indexOf(".");
        if (a > 0) {
            //获取小数点后面的数字
            String dianAfter = strNum.substring(a + 1);
            if (dianAfter.length() >= 2) {
                ss = strNum.substring(0, a + 3);
            } else {
                ss = strNum + "0";
            }
        } else {
            ss = strNum + ".00";
        }
        return ss;
    }
}
